# ==========================================================
# 终极解决方案 V2：强制使用 'Agg' 后端
# 这段代码必须放在所有 matplotlib 相关导入之前！
import matplotlib
matplotlib.use('Agg') 
# ==========================================================

import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import matplotlib.pyplot as plt
import seaborn as sns
import os

print("--- Running Task 1: Wine Data Dimensionality Reduction (Ultimate Version) ---")
print("INFO: Using 'Agg' backend. No plot window will be shown on screen.")

# 1. Load Data
col_names = [
    'class_label', 'alcohol', 'malic_acid', 'ash', 'alcalinity_of_ash',
    'magnesium', 'total_phenols', 'flavanoids', 'nonflavanoid_phenols',
    'proanthocyanins', 'color_intensity', 'hue',
    'od280/od315_of_diluted_wines', 'proline'
]
data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'
wine_df = pd.read_csv(data_url, header=None, names=col_names)
print("Successfully loaded Wine dataset from UCI.")

# 2. Filter data
wine_subset = wine_df[wine_df['class_label'].isin([1, 2])].copy()
print(f"Filtered data. New dataset has {len(wine_subset)} records.")

# 3. Separate features and labels
X = wine_subset.drop('class_label', axis=1)
y = wine_subset['class_label']

# 4. Standardize data
X_scaled = StandardScaler().fit_transform(X)
print("Data standardization complete.")

# 5. PCA
print("\n--- Performing PCA ---")
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
print("PCA results (first 20 rows):")
print(pd.DataFrame(X_pca, columns=['Principal Component 1', 'Principal Component 2']).head(20))

# 6. LDA
print("\n--- Performing LDA ---")
lda = LinearDiscriminantAnalysis(n_components=1)
X_lda = lda.fit_transform(X_scaled, y)
print("LDA results (first 20 rows):")
print(pd.DataFrame(X_lda, columns=['Linear Discriminant 1']).head(20))

print("\nPlotting dimensionality reduction results...")

sns.set_style('whitegrid')
fig, axes = plt.subplots(1, 2, figsize=(14, 6))

# Plot PCA results
sns.scatterplot(x=X_pca[:, 0], y=X_pca[:, 1], hue=y, palette='viridis', ax=axes[0])
axes[0].set_title('PCA Results (2D)', fontsize=15)
axes[0].set_xlabel('Principal Component 1', fontsize=12)
axes[0].set_ylabel('Principal Component 2', fontsize=12)
axes[0].legend(title='Class')

# Plot LDA results
sns.scatterplot(x=X_lda.flatten(), y=np.zeros(len(X_lda)), hue=y, palette='viridis', ax=axes[1])
axes[1].set_title('LDA Results (1D)', fontsize=15)
axes[1].set_xlabel('Linear Discriminant 1', fontsize=12)
axes[1].get_yaxis().set_visible(False)
axes[1].legend(title='Class')

# --- Save the figure and print the full path ---
plt.tight_layout()
image_filename = 'task1_visualization_GUARANTEED.png'
save_path = os.path.join(os.getcwd(), image_filename)

try:
    plt.savefig(save_path, dpi=300)
    print("\n" + "="*50)
    print(f"!!! IMAGE SAVED SUCCESSFULLY !!!")
    print(f"Full path: {save_path}")
    print("Please check your folder now.")
    print("="*50 + "\n")
except Exception as e:
    print("\n" + "X"*50)
    print(f"ERROR: Failed to save the image.")
    print(f"The error was: {e}")
    print("X"*50 + "\n")



print("--- Task 1 finished ---")